package cn.oowoo.rabbitmq.limit;

import cn.oowoo.rabbitmq.config.RabbitConfig;
import cn.oowoo.rabbitmq.config.RabbitExchangeTypeEnum;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
 * @Author ZhangBin
 * @Date 2021/5/8 13:48
 * @Description: 消费端无限流测试-消费者
 *
 **/
public class NoLimitConsumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = RabbitConfig.createConnection();
        // 创建消息通道
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(RabbitConfig.EXCHANGE_LIMIT_NAME, RabbitExchangeTypeEnum.TOPIC.getExchangeType(),true,false,null);
        channel.queueDeclare(RabbitConfig.QUEUE_NO_LIMIT_NAME, true, false, false, null);
        //channel.basicQos(0, 3, false);
        channel.queueBind(RabbitConfig.QUEUE_NO_LIMIT_NAME, RabbitConfig.EXCHANGE_LIMIT_NAME, "limit.*.key");

        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                String msg = new String(body, "UTF-8");
                System.out.println("Received message : " + msg);
                channel.basicAck(envelope.getDeliveryTag(), true);
            }
        };
        /**
         * autoAck= false :关闭自动确认，也就是开启手动确认
         * 开始获取消息，注意这里开启了手工应答（关闭自动应答）
         * String basicConsume(String queue, boolean autoAck, Consumer callback)
         *
         */
        channel.basicConsume(RabbitConfig.QUEUE_NO_LIMIT_NAME, false, consumer);
    }
}
